// pages/community/index.js
import { proxy, getCommunityIndexdata, getWonderfulGroupPhotos, joinGroups, communityFollow, communityUNfollow, communityAlilog, _getUserInfo } from '../../utils/community_util.js';
import { reqHeader, isAuthorization, banPNG } from '../../utils/util.js';
import Swiper from '../../pages/detail/swiperInfo.js';
import LoginStore from '../../pages/login/store.js';
import Store from './contestStore';
import UploadStore from './upload/store.js';
import PhotoselectStore from '../photoselectcommunity/store.js';
import { encode } from '../../libs/querystring/index.js';
const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    navbarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '', //导航栏 中间的标题
      background: 'linear-gradient(to bottom, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0))',
      hasFilter: true,
      color: '#FFFFFF',
      btnStyle: 'white', //black, white
    },
    navBarHeight: app.globalData.height,
    isrecommendMembers:false,//是否有推荐摄影师
    appParams:'',//跳转app参数
    gettribeId:'',//部落ID
    members:[],//推荐摄影师
    wonderfulGroups:[],//精选集
    avatar:'',//部落头像
    community_name:'',//部落名称
    contestNumber:0,//活动数
    userNumber:0,//成员
    photoNumber: 0,//作品数
    wonderfulSets:[],//精选集
    tribeWonderfulGroupId:'',
    qualify:'',//申请加入的话术
    cover:'',
    auth_blue:'../../icon/auth_blue.png',
    auth_green:'../../icon/auth_green.png',
    auth_red:'../../icon/auth_red.png',
    auth_black:'../../icon/auth_black.png',
    auth_url:'',
    nowonderfulSets:'../../icon/icon_empty_tribe@3x.png',
    auth_show:true,
    join_show:false,//加入申请显示与隐藏
    inputValue:'',
    btnstatus:0,//加入按钮的状态 0 未登录，1 已登录未加入，2 已登录 未加入 已申请，3 已登录 已加入 4,关注 5 已关注
    join_show_up:'',//输入框距离上面的高度控制
    join_show_up_state:true,
    showTheme:false,//投稿显示选择
    nickname:'',
  },
  //gotoapp
  gotoapp(){
    //埋点 点击打开app
    communityAlilog('mini-program-tribe-profile-click-open-app');
    //埋点 点击打开app
  },
  //投稿
  _submitAction(e) {
    console.log(e)
      this.setData({
        showTheme: true
      })
    //埋点 点击投稿
    communityAlilog('mini-program-tribe-profile-click-submit');
    //埋点 点击投稿
  },
  hideModal: function (p) {
    // this.setData({
    //   showTheme: false
    // })
    let childs = this.selectComponent("#choose");
    childs.closePop();
    setTimeout(() => {
      let obj = {};
      if (this.data.showTheme) {
        obj.showTheme = false;
      }
      if (this.data.showModalStatus) {
        obj.showModalStatus = false;
      } else if (typeof (p) === "string") {
        obj.showModalStatus = true;
      }

      this.setData(obj);
    }, childs.data.time)
  },
  takePoto: function () {
    Store.takePhoto((path) => {
      this.uploadImage({
        filePath: path
      });
    })
    },
  uploadImage(opts) {
    // debugger;
    UploadStore.setFilePath(opts.filePath);
    // UploadStore.setSelectedCategoryId(this.data.selectedCategoryId);
    wx.navigateTo({
      url: '/pages/editPhotocommunity/editPhoto'
    });
  },
  _selectMyphoto() {
    let getUrl = (resourceType) => {
      var urlParamstr = encode({
        access_token: LoginStore.userInfo.access_token,
        // client_type: 1,
        resourceType: 'photoAndGroup',
        targetId: wx.getStorageSync('tribeId'),
        from:'tribe',
        // contestId: Store.cur_contest.id
      });
      return `${proxy}/community/user/obtainPersonalResource?` + urlParamstr
    }
    let resourceType = '';
    // if (Store.photo && !Store.groupPhoto) {
    //   resourceType = '0'
    // } else if (!Store.photo && Store.groupPhoto) {
    //   resourceType = '2'
    // } else if (Store.photo && Store.groupPhoto) {
      resourceType = 'all'
    // }
    PhotoselectStore.setAjaxUrl(getUrl('photoAndGroup'));
    wx.navigateTo({
      url: `/pages/photoselectcommunity/photoselect?fromCommunity=true`
    });
  },
  //输入框获取焦点时触发的方法
  inputfocus(e){
    console.log(e.detail);
    wx.pageScrollTo({
      scrollTop:150
    })
    this.setData({
      join_show_up_state:false
    })
  },
  inputblur(e){
    wx.pageScrollTo({
      scrollTop: 0
    })
    // this.setData({
    //   join_show_up_state: true,
    // })
  },
  //关闭加入申请
  joinClose(){
    if (this.data.join_show_up_state){
      this.setData({
        join_show: false,
        inputValue: '',
      })
    }else{
      this.setData({
        join_show_up_state: true,
      })
    }
    
  },
  //申请加入
  applytoJoin(){
    //埋点 展示加入弹窗
    communityAlilog('mini-program-tribe-profile-show-apply-window');
    //埋点 展示加入弹窗
    this.setData({
      join_show: true,
    })
  },
  //绑定申请加入的input
  inputeidt(e){
    this.setData({
      inputValue: e.detail.value,
    })
    console.log(this.data.inputValue);
  },
  //发送申请后的回调函数
  joinGroupscallback(res){
    console.log(res);
    if(res.data.status == '500'){
      console.log('跳转')
      wx.showModal({
        title: '提示',
        content: '未登录，去登陆？',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            wx.redirectTo({
              url: '/pages/login/login'
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      wx.showToast({
        title: '已提交申请',
        icon: 'success',
        duration: 2000
      })
      this.setData({
        join_show: false,
        btnstatus:2,
      })
    }
  },
  //申请加入按钮
  applyjoinfunc(){
    //埋点 点击加入申请提交按钮
    communityAlilog('mini-program-tribe-profile-submit-apply');
    //埋点 点击加入申请提交按钮
    console.log(this.data.inputValue);
    joinGroups({ reason: this.data.inputValue, tribeId:this.data.gettribeId }, this.joinGroupscallback)
  },
  // 获取首页的相关信息
  getAlldata(res) {
    console.log(res);
    let restribe = res.tribe;
    let that = this;
    // debugger;
    if (typeof restribe.status == 'undefined' || restribe.status == 'join'){
      console.log('申请加入')
      if (res.joinState) {
        if (res.joinState == 'UNJOIN') {
          this.setData({
            btnstatus: 1
          })
        } else if (res.joinState == 'JOIN') {
          this.setData({
            btnstatus: 3
          })
        } else {
          this.setData({
            btnstatus: 2
          })
        }
      }
    }else if ( restribe.status == 'follow' && res.followState == false){
      if (res.followState == false){
        console.log('关注加入')
        this.setData({
          btnstatus: 4
        })
      }else{
        this.setData({
          btnstatus: 5
        })
      }
      
    }
    if (res.joinState == 'JOIN') {
      this.setData({
        btnstatus: 3
      })
    }
    console.log(this.data.btnstatus)
    let membersdata = [], wonderfulGroups = [], cover='', qualify='';
    restribe.indexData.map(item => {
      if (item.recommendMembers && item.recommendMembers.length !== 0) {
        that.setData({
          isrecommendMembers: true,
          members: item.recommendMembers
        })
      } else if (item.members) {
        that.setData({
          members: item.members
        })
      }
    });
    console.log(this.data.isrecommendMembers);
    //随机获取部落背景图
    let picnum = 0,pic_cover = ''
    restribe.indexData.map(item => {
      if (item.wonderfulGroups && item.wonderfulGroups.length !== 0) {
        // item.wonderfulGroups.map(item => {
        //   if (item.photoNum >= 1){
        //     wonderfulGroups.push(item);
        //   }
        // })
        // console.log(item.wonderfulGroups)
        wonderfulGroups = item.wonderfulGroups
        pic_cover = wonderfulGroups[0].cover.baseUrl
      }

    })
    if (restribe.wonderfulPhotos && restribe.wonderfulPhotos.length !== 0) {
      picnum = Math.floor(Math.random() * restribe.wonderfulPhotos.length);
      console.log(restribe.wonderfulPhotos.length, picnum);
      cover = restribe.wonderfulPhotos[picnum].url.baseUrl;
    }else{
      cover = pic_cover
    }
     console.log(wonderfulGroups)
    if (restribe.qualify){
      qualify = restribe.qualify
    } else {
      qualify = ''
    }
    this.setData({
      avatar: restribe.avatar.a1 ? restribe.avatar.a1 : 'https://img.500px.me/default_tx.png!a1',
      wonderfulGroups: wonderfulGroups,
      community_name: restribe.name,
      contestNumber: restribe.contestNumber,//活动数
      userNumber: restribe.userNumber,//成员
      photoNumber: restribe.photoNumber,//作品数
      cover: cover,
      qualify: qualify,
    });
    if (restribe.authentication == "OFFICIAL" || restribe.authentication == "BLUE"){
      this.setData({
        auth_url: this.data.auth_blue
      })
    } else if (restribe.authentication == "RED"){
      this.setData({
        auth_url: this.data.auth_red
      })
    } else if (restribe.authentication == "GREEN"){
      this.setData({
        auth_url: this.data.auth_green
      })
    } else if (restribe.authentication == "BLACK"){
      this.setData({
        auth_url: this.data.auth_black
      })
    } else if (restribe.authentication == "NOT_AUTHENTICATION") {
      this.setData({
        auth_show: false
      })
    }  

    this.setData({
      appParams: JSON.stringify({
        category: "tribeDetail",
        id: this.data.gettribeId
      })
    })
    wx.stopPullDownRefresh();
  },
  //推荐摄影师页面
  gotoSuggestshooter: function(e){
    //埋点 点击摄影师头像
    communityAlilog('mini-program-tribe-profile-click-photographer-avatar');
    //埋点 点击摄影师头像
    var sid = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/userInfo/userInfo?userId=' + sid
    });
  },
  //获取精选集数据
  getdatafromwonderfulSets:function(data){
     console.log(data);
    let wonderdata =[];
    data.data.data.map(item => {
      if (item.resourceType !== 3){
        wonderdata.push(item);
      }
    })
    console.log(wonderdata);
    Swiper.setData({
      imgUrls: wonderdata,
      urlStr: '/community/tribe/listTribeWonderfulGroupPhotosV2',
      params: {
        tribeId: wx.getStorageSync('loginData'),
        tribeWonderfulGroupId: this.data.wonderfulSetsId,
        page:1,
        size:10,
        wxApp: true,
      },
      hasNext: true,
      selectedID: wonderdata[0].id,
    });

    let urlStr = `/pages/detail/detail?id=${wonderdata[0].id}&resourceType=${wonderdata[0].resourceType}`;
    let pageList = getCurrentPages();
    if (pageList.length >= 8) {
      wx.redirectTo({
        url: urlStr,
      })
    } else {
      wx.navigateTo({
        url: urlStr
      });
    }
  },
  //进入精选集
  gotowonderfulSets:function(e){
    //埋点 点击部落精选
    communityAlilog('mini-program-tribe-profile-click-gallery');
    //埋点 点击部落精选
    var wonderfulSetsId = e.currentTarget.dataset.setsid;
    this.setData({
      tribeWonderfulGroupId: wonderfulSetsId,
    })
    getWonderfulGroupPhotos({ 'tribeWonderfulGroupId': wonderfulSetsId, 'tribeId': this.data.gettribeId}, this.getdatafromwonderfulSets)
  },
  //登录相关操作
  toUserInfo: function (e) {
    if (!isAuthorization(e)) {
      return;
    }
    LoginStore.validateLogin(() => {
      let userId = LoginStore.userInfo.userId;
      getCommunityIndexdata({ 'tribeId': this.data.gettribeId}, this.getAlldata);
    });
  },
  //关注或者取消关注以后的callback
  followCallback(res){
    console.log(res);
    getCommunityIndexdata({ 'tribeId': this.data.gettribeId }, this.getAlldata);
  },
  // 特殊部落处理关注与取消关注
  _community_follow(){
    console.log('关注')
    communityFollow(this.followCallback)
  },
  _community_unfollow(){
    console.log('取消关注')
    communityUNfollow(this.followCallback)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //埋点 页面加载次数
    communityAlilog('mini-program-tribe-profile-pageload');
    //埋点 页面加载次数

    let gettribeId = ''
    console.log(options);
    if(options.tribeId){
      gettribeId = options.tribeId
    } else {
      //gettribeId = 'bea5bba647174cb4afac13dd9d5adaba'
      //gettribeId = '471ade40196a41ef9b5c4b6210e34cfe'

      //gettribeId = 'd1ed8d6e73b94df289791049aa9f9c22'
      //gettribeId = '3568350c6d824b9bb97a2a32adf4ef93'
      //gettribeId = '58e95a9494674de9ad2873fa96875df6'
      //gettribeId = '0c0e9faab6774af7bf50b86d3bd82a38'
      //gettribeId = '587dcd83426a47478fb33ca3ab43ed3d'
      //gettribeId = '12dfc91655e04850b3b57638b03cf267'
      gettribeId = wx.getStorageSync('tribeId') //上线以后确认
      wx.showToast({
        title: '没有部落id',
        icon: 'success',
        duration: 2000
      })

    }
    wx.setStorageSync('tribeId', gettribeId);
    console.log(gettribeId);
    this.setData({
      'gettribeId': gettribeId
    })
    console.log("这里是验证部落ID存不存在"+gettribeId)
    console.log(wx.getStorageSync('loginData'));
    let loginData = wx.getStorageSync('loginData');
    console.log(loginData)
    if (loginData !== ''){
      //已登录
      getCommunityIndexdata({'tribeId': gettribeId}, this.getAlldata);
    }else{
      //未登录
      getCommunityIndexdata({ 'tribeId': gettribeId }, this.getAlldata);
      this.setData({
        btnstatus:0,
      })
    }
    //获取用户昵称
    _getUserInfo(this.getusername);
  },
 
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    getCommunityIndexdata({ 'tribeId':wx.getStorageSync('tribeId')}, this.getAlldata);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function (res) {
  //   let nickname = LoginStore.userInfo.nickName ? LoginStore.userInfo.nickName : '';
  //   //community_name
  //   if(res.from === 'button'){
  //     // console.log(res.target,res);
  //     return {
  //       title: nickname + '邀请你向' + '「' + this.data.community_name +'」'+ '部落投稿',
  //       // desc: '自定义分享描述',
  //       // path: '/page/user?id=123'
  //     }

  //   }
  // },

// 
getusername(res){
  console.log(res);
  if (res.statusCode == 200 && res.errMsg == "request:ok"){
    this.setData({
      nickname: res.data.data.nickName,
    })
  }
},
onShareAppMessage(res) {
  
    //转发时携带 shareTicket才能在回调中获取到shareTickets
  // let nickname = LoginStore.userInfo.nickName ? LoginStore.userInfo.nickName : '';
    wx.showShareMenu({
      withShareTicket: true
    }) 

  if (res.from === 'button') {
    //埋点 分享点击次数
    communityAlilog('mini-program-tribe-profile-click-share');
    //埋点 分享点击次数

    return {
      title: this.data.nickname + '邀请你向' + '「' + this.data.community_name + '」' + '部落投稿',
      // success: res => {
      //   console.log('--- 转发回调 ---', res);
      //   //onShareAppMessage回调的shareTickets，如果没有，就说明不是转发到群聊的
      //   console.log('--- shareTickets ---', res.shareTickets);
      //   //转发到群里的才会有shareTickets
      //   if(res.shareTickets && res.shareTickets[0]) {
      //       //获取转发的详细信息
      //       wx.getShareInfo({
      //         shareTicket: res.shareTickets[0],
      //         success: res => {
      //           console.log('--- 错误信息 ---', res.errMsg);
      //           console.log('--- 包括敏感数据在内的完整转发信息的加密数据 ---', res.encryptedData);
      //           console.log('--- 错误信息 ---', res.iv);
      //         },
      //         fail: error => {
      //           console.log('--- getShareInfo fail ---', error);
      //         }
      //       })
      //     }
      // },
      // fail: () => {
      //   console.log('--- 转发失败 ---', path);
      //   }
      }
    }
  }
// 

})